<template>
  <Row>
    <Col span="17">
      <Input v-model:value="namespace" />
    </Col>
    <Col span="7" style="text-align: right" class="btn-group">
      <Button type="default" :danger="enableAttributes" @click="enableAttributes = !enableAttributes">
        <CodeFilled />
        {{ enableAttributes ? 'Dapper实体' : '普通对象' }}
      </Button>
      <Button type="primary" @click="onCopyScript"> <CopyFilled />复制代码 </Button>
    </Col>
  </Row>
  <Row>
    <pre id="scripts" :style="contentStyle">
using System;<template v-if="enableAttributes">
using System.ComponentModel.DataAnnotations;
using Mercury.Prime.Core;</template>

namespace {{ namespace }}.{{ enableAttributes ? 'Entities' : 'Queries.Responses' }}
{
    /// &lt;summary>
    /// {{ }}实体
    /// &lt;/summary><template v-if="enableAttributes">
    [Table("{{ props.tableName }}")]</template>
    public class {{ pascal(className) }}
    {
        #region Properties
      <span v-for="item in columns">
        /// &lt;summary>
        /// {{ item.column_comment || item.column_name }}
        /// &lt;/summary><span v-for="attr in getAttributes(item)">
        {{ attr }}</span>
        public {{ codeType(item.column_type) }} {{ pascal(item.column_name) }} { get; set; }
      </span>
        #endregion
    }
}</pre>
  </Row>
</template>
<script setup>
  import { useStore } from 'vuex';
  import { ref, inject, watch, computed, onMounted } from 'vue';
  import { Row, Col, Input, Button } from 'ant-design-vue';
  import { CodeFilled, CopyFilled } from '@ant-design/icons-vue';

  import { codeType, pascal } from '@/libs/helpers.js';

  const $store = useStore();
  const $http = inject('$http');
  const $message = inject('$message');
  const $copyText = inject('$copyText');

  const props = defineProps({
    dbIndex: String,
    dbType: String,
    schema: String,
    tableName: String
  });

  const columns = ref([]);
  const enableAttributes = ref(false);
  const namespace = ref('');

  const className = computed(() => (columns.value[0] || { tableName: props.tableName }).tableName);

  const contentStyle = computed(() => {
    let maxHeight = $store.state.area.content.height - 130 + 'px';

    return {
      'min-height': maxHeight,
      'max-height': maxHeight
    };
  });

  watch(
    () => props.tableName,
    () => GetColumns()
  );

  watch(namespace, () => {
    localStorage.setItem('$namespace$', namespace.value);
  });

  function GetColumns() {
    let dbIndex = props.dbIndex;
    let dbType = props.dbType;
    let schema = props.schema;
    let tableName = props.tableName;

    if (dbIndex && schema && tableName) {
      $http.get(`/api/db/${dbIndex}/${schema}/${tableName}/columns`).then(res => (columns.value = res.datas));
    }
  }

  function getAttributes(item) {
    let rs = [];

    if (!enableAttributes.value) {
      return rs;
    }

    let columnAttr = `[Column("${item.column_name}"`;
    let primaryKey = item.column_key == 1 || item.column_key == 'PRI';
    let nullable = item.is_nullable == 1 || item.is_nullable == 'YES';

    if (primaryKey) {
      columnAttr += `, IsPrimaryKey = true`;
    } else {
      columnAttr += `, IsNullable = ${nullable ? 'true' : 'false'}`;
    }

    rs.push(`${columnAttr})]`);

    if (primaryKey || !nullable) {
      rs.push(`[Required(AllowEmptyStrings = false, ErrorMessage = "${item.column_comment}不能为空！")]`);
    }

    let columnType = item.column_type.toLowerCase();

    if (columnType.indexOf('char') != -1 && columnType.indexOf('max') == -1) {
      let counter = columnType.indexOf('n') != -1 ? 2 : 1;

      rs.push(`[StringLength(${item.character_length / counter}, ErrorMessage = "${item.column_comment}字符长度不能超过{1}个字符！")]`);
    }

    return rs;
  }

  function onCopyScript() {
    $copyText(document.getElementById('scripts').innerText).then(() => {
      $message.success('代码已复制！');
    });
  }

  onMounted(() => {
    namespace.value = localStorage.getItem('$namespace$') || 'Mercury.AuthCenter';
    
    GetColumns();
  });
</script>
